package com.hu.system.service.impl;

import com.hu.common.utils.SecurityUtils;
import com.hu.system.mapper.DashboardMapper;
import com.hu.system.mapper.SysUserShopMapper;
import com.hu.system.service.IDashboardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 首页仪表盘Service业务层处理
 *
 * @author hu
 * @date 2025-01-22
 */
@Service
public class DashboardServiceImpl implements IDashboardService {

    @Autowired
    private DashboardMapper dashboardMapper;

    @Autowired
    private SysUserShopMapper userShopMapper;

    /**
     * 获取当前用户的店铺ID列表（数据权限）
     */
    private List<Long> getCurrentUserShopIds() {
        Long userId = SecurityUtils.getUserId();

        // 管理员返回null，查看全部数据
        if (userId != null && userId == 1L) {
            return null;
        }

        // 普通用户返回绑定的店铺ID列表
        List<Long> shopIds = userShopMapper.selectShopIdsByUserId(userId);
        if (shopIds == null || shopIds.isEmpty()) {
            return new ArrayList<>();
        }

        return shopIds;
    }

    @Override
    public Map<String, Object> getStatistics() {
        List<Long> shopIds = getCurrentUserShopIds();

        Map<String, Object> result = new HashMap<>();
        result.put("shopCount", dashboardMapper.countShops(shopIds));
        result.put("productCount", dashboardMapper.countProducts(shopIds));
        result.put("stockTotal", dashboardMapper.countStockTotal(shopIds));
        result.put("purchaseAmountThisMonth", dashboardMapper.sumPurchaseAmountThisMonth(shopIds));

        return result;
    }

    @Override
    public List<Map<String, Object>> getPurchaseTrend() {
        List<Long> shopIds = getCurrentUserShopIds();
        return dashboardMapper.selectPurchaseTrend(shopIds, 30);
    }

    @Override
    public List<Map<String, Object>> getProductStatus() {
        List<Long> shopIds = getCurrentUserShopIds();
        return dashboardMapper.selectProductStatus(shopIds);
    }

    @Override
    public List<Map<String, Object>> getStockWarning() {
        List<Long> shopIds = getCurrentUserShopIds();
        return dashboardMapper.selectStockWarning(shopIds, 50);
    }

    @Override
    public List<Map<String, Object>> getProfitWarning() {
        List<Long> shopIds = getCurrentUserShopIds();
        return dashboardMapper.selectProfitWarning(shopIds, 25.0);
    }
}

